import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import {
  getToken,
  getTokenTime,
  getrefreshToken,
  getrefreshtokenTime,
} from "@/utils/auth";

import { gotoLogin, handleBigNumbers } from "@/utils/index";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

// request interceptor
service.interceptors.request.use(
  async (config) => {
    // 判断Token和refreshToken逻辑
    const notNeedToken = config.headers.notNeedToken;
    if (notNeedToken) {
      delete config.headers.notNeedToken;
      return config;
    }
    const Token = store.getters.token;
    const refreshToken = store.getters.refreshToken;
    const tokenTime = getTokenTime();
    const refreshTokenTime = getrefreshtokenTime();
    if (Token && refreshToken && tokenTime && refreshTokenTime) {
      const nowTime = Math.floor(Date.now() / 1000);
      // console.log("nowTime:", nowTime);
      if (nowTime < tokenTime) {
        // 正常流程
        config.headers["Authorization"] = "Bearer " + getToken();
        return config;
      } else if (nowTime > tokenTime && nowTime < refreshTokenTime) {
        // Token过期，刷新Token后继续进行请求
        try {
          // 调用刷新 Token 的逻辑
          await store.dispatch("user/refreshToken");
          // 刷新成功后，重新设置 Token 到请求头
          config.headers["Authorization"] = "Bearer " + getToken();
          // 重新发送请求
          return service(config);
        } catch (error) {
          // 刷新 Token 失败，跳转到登录页面
          gotoLogin();
          return Promise.reject(error);
        }
      } else if (nowTime > refreshTokenTime) {
        // 跳转登录页面重新登录
        gotoLogin();
        return Promise.reject(new Error("Token and Refresh Token expired"));
      }
    } else {
      // 跳转登录页面重新登录
      gotoLogin();
      return Promise.reject(new Error("No Token or Refresh Token found"));
    }
  },
  (error) => {
    console.log("Request Error:", error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    const Token = store.getters.token;
    const refreshToken = store.getters.refreshToken;
    const tokenTime = getTokenTime();
    const refreshTokenTime = getrefreshtokenTime();
    // console.log("Response:", response); // 添加响应日志
    let res = response.data;
    if (response.status === 200) {
      if (res.success) {
        res = handleBigNumbers(res);
        return res;
      } else {
      }
    } else {
      if (response.status === 405) {
        // 去比较tokenTime和refreshTokenTime和现在的时间大小做处理
      }
    }
    // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 20000) {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })

    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // to re-login
    //     MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //       confirmButtonText: 'Re-Login',
    //       cancelButtonText: 'Cancel',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         location.reload()
    //       })
    //     })
    //   }
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    //   return res
    // }
  },
  (error) => {
    console.log("Response Error:", error.response || error); // 添加详细错误日志
    console.log("Error Config:", error.config); // 添加错误请求配置日志
    Message({
      message: error.message ?? "错误",
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
